package com.wedo.mall.activity.user;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.e.library.activity.EActivity;
import com.e.library.http.EApi;
import com.e.library.http.EObserver;
import com.e.library.http.EResponse;
import com.e.library.listener.EListener;
import com.e.library.widget.ETitleBar;
import com.wedo.mall.R;
import com.wedo.mall.adapter.PhotoAdapter;
import com.wedo.mall.entity.GoodsList;
import com.wedo.mall.entity.GoodsRecordItem;
import com.wedo.mall.entity.OrderData;
import com.wedo.mall.util.DateUtils;
import com.wedo.mall.util.WUrl;
import com.wedo.mall.util.WUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import me.iwf.photopicker.PhotoPicker;

/**评价*/
public class EvaluateActivity extends EActivity {

    public static final String EXTRA_GOODS = "goods";
    public static final String EXTRA_ORDER_DATA = "orderData";
    public static final String EXTRA_GOODS_LIST = "goodsList";
    public static final String EXTRA_ORDER_SN = "order_sn";
    private SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");

    @BindView(R.id.title_bar) ETitleBar title_bar;
    @BindView(R.id.tv_order_sn) TextView tv_order_sn;
    @BindView(R.id.tv_order_time) TextView tv_order_time;
    @BindView(R.id.tv_goodname) TextView tv_goodname;
    @BindView(R.id.tv_price) TextView tv_price;
    @BindView(R.id.tv_gooddescribe) TextView tv_gooddescribe;
    @BindView(R.id.tv_number) TextView tv_number;
    @BindView(R.id.iv_goodicon) ImageView iv_goodicon;
    @BindView(R.id.iv_star2) ImageView iv_star2;
    @BindView(R.id.iv_star3) ImageView iv_star3;
    @BindView(R.id.iv_star4) ImageView iv_star4;
    @BindView(R.id.iv_star5) ImageView iv_star5;
    @BindView(R.id.et_content) EditText et_content;
    @BindView(R.id.rv_list) RecyclerView rv_list;

    private int endpoint;
    private GoodsRecordItem goods;
    private String star;
    public ArrayList<String> mSelectedPhotos = new ArrayList<>(9);//已选照片
    private ArrayList<String> mPendingPhotos = new ArrayList<>();//待上传图片
    public List<String> mUploadPhotos = new ArrayList<>();//已上传图片
    private PhotoAdapter mPhotoAdapter;

    public static void toEvaluate(EActivity activity,OrderData orderData,GoodsList goodsList){

        /**兼容处理评价*/
        GoodsRecordItem item = new GoodsRecordItem();
        item.order_sn = orderData.order_sn;
        item.add_time = orderData.add_time;
        item.attr_list = goodsList.attr_list;
        item.goods_id = goodsList.goods_id;
        item.goods_name = goodsList.goods_name;
        item.goods_image = goodsList.goods_image;
        item.goods_number = goodsList.goods_number;
        item.price = goodsList.price;

        toEvaluate(activity,item,0);
    }

    public static void toEvaluate(EActivity activity,GoodsRecordItem goods){
        toEvaluate(activity,goods,1);
    }

    public static void toEvaluate(EActivity activity,GoodsRecordItem goods,int endpoint){
        Bundle bundle = new Bundle();
        bundle.putParcelable(EXTRA_GOODS,goods);
        bundle.putInt("endpoint",endpoint);
        activity.toActivity(EvaluateActivity.class,bundle);
    }

    @Override
    protected int layout() {
        return R.layout.activity_evaluate;
    }

    @Override
    protected void onActivityCreated(Bundle state) {
        title_bar.setForwardText(R.string.submit);
        title_bar.showForwordTv();
        title_bar.setForwardTextColor(getResources().getColor(R.color.user_addresslist_font));

        mSelectedPhotos = new ArrayList<>();
        mUploadPhotos = new ArrayList<>();
        star = "5";

        goods = getIntent().getParcelableExtra(EXTRA_GOODS);
        endpoint = getIntent().getIntExtra("endpoint",0);

        tv_order_sn.setText(goods.order_sn);
        tv_order_time.setText(DateUtils.convert(format,Integer.parseInt(goods.add_time)));
        tv_goodname.setText(goods.goods_name);
        tv_price.setText("RM"+goods.price);
        tv_gooddescribe.setText(goods.attr_list);
        tv_number.setText("X"+goods.goods_number);
        Glide.with(this).load(WUrl.url(goods.goods_image)).error(R.drawable.place_holder_goods).placeholder(R.drawable.place_holder_goods).diskCacheStrategy(DiskCacheStrategy.ALL).into(iv_goodicon);

        rv_list.setHasFixedSize(true);
        rv_list.setNestedScrollingEnabled(false);
        rv_list.setLayoutManager(new GridLayoutManager(this,4));
        mPhotoAdapter = new PhotoAdapter(this, mSelectedPhotos);
        rv_list.setAdapter(mPhotoAdapter);
        mPhotoAdapter.setItemClickListener(new EListener<String>() {
            @Override
            public void onInvoked(View view, String data, int position) {
                if (position == mSelectedPhotos.size() || TextUtils.isEmpty(data)) {
                    onPortraitClick();
                }
            }
        });

    }

    protected void onPortraitClick(){
        PhotoPicker.builder()
                .setPhotoCount(9)
                .setShowCamera(true)
                .setShowGif(false)
                .setPreviewEnabled(true)
                .setSelected(mSelectedPhotos)
                .start(EvaluateActivity.this, PhotoPicker.REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode !=RESULT_OK || data == null) return;

        switch (requestCode){
            case PhotoPicker.REQUEST_CODE:
                ArrayList<String> photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                mPhotoAdapter.refresh(photos);
                break;
        }
    }

    @OnClick(R.id.iv_star1)
    protected void onStar1Click(){
        star = "1";
        iv_star2.setImageDrawable(getResources().getDrawable(R.drawable.purple_star_empty));
        iv_star3.setImageDrawable(getResources().getDrawable(R.drawable.purple_star_empty));
        iv_star4.setImageDrawable(getResources().getDrawable(R.drawable.purple_star_empty));
        iv_star5.setImageDrawable(getResources().getDrawable(R.drawable.purple_star_empty));
    }

    @OnClick(R.id.iv_star2)
    protected void onStar2Click(){
        star = "2";
        iv_star2.setImageDrawable(getResources().getDrawable(R.drawable.purple_star_full));
        iv_star3.setImageDrawable(getResources().getDrawable(R.drawable.purple_star_empty));
        iv_star4.setImageDrawable(getResources().getDrawable(R.drawable.purple_star_empty));
        iv_star5.setImageDrawable(getResources().getDrawable(R.drawable.purple_star_empty));
    }

    @OnClick(R.id.iv_star3)
    protected void onStar3Click(){
        star = "3";
        iv_star2.setImageDrawable(getResources().getDrawable(R.drawable.purple_star_full));
        iv_star3.setImageDrawable(getResources().getDrawable(R.drawable.purple_star_full));
        iv_star4.setImageDrawable(getResources().getDrawable(R.drawable.purple_star_empty));
        iv_star5.setImageDrawable(getResources().getDrawable(R.drawable.purple_star_empty));
    }

    @OnClick(R.id.iv_star4)
    protected void onStar4Click(){
        star = "4";
        iv_star2.setImageDrawable(getResources().getDrawable(R.drawable.purple_star_full));
        iv_star3.setImageDrawable(getResources().getDrawable(R.drawable.purple_star_full));
        iv_star4.setImageDrawable(getResources().getDrawable(R.drawable.purple_star_full));
        iv_star5.setImageDrawable(getResources().getDrawable(R.drawable.purple_star_empty));
    }

    @OnClick(R.id.iv_star5)
    protected void onStar5Click(){
        star = "5";
        iv_star2.setImageDrawable(getResources().getDrawable(R.drawable.purple_star_full));
        iv_star3.setImageDrawable(getResources().getDrawable(R.drawable.purple_star_full));
        iv_star4.setImageDrawable(getResources().getDrawable(R.drawable.purple_star_full));
        iv_star5.setImageDrawable(getResources().getDrawable(R.drawable.purple_star_full));
    }

    @OnClick(R.id.tv_forward)
    protected void onSubmitClick(){
        if (TextUtils.isEmpty(et_content.getText().toString())){
            return;
        }

        mPendingPhotos.clear();
        mUploadPhotos.clear();

        if (!mSelectedPhotos.isEmpty()){
            mPendingPhotos.addAll(mSelectedPhotos);
            loading();
            upload();
        }else {
            addGoodsComment();
        }
    }

    /**
     * 上传图片
     */
    private void upload(){
        String imgStr = WUtils.toBase64(mSelectedPhotos.get(0));
        Observable<EResponse> observable = api().upload(imgStr,"User");
        observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                mUploadPhotos.add(response.string("image"));
                mPendingPhotos.remove(0);
                if(mPendingPhotos.size() > 0){
                    upload();
                }else{
                    addGoodsComment();
                }
            }

            @Override
            public void failure(String msg) {
                dismiss(msg);
            }
        });
    }

    /**
     * 提交评价
     */
    public void addGoodsComment(){
        Map<String,String> params = new HashMap<>();
        params.put(EXTRA_ORDER_SN,goods.order_sn);
        params.put("goods_id",goods.goods_id);
        params.put("star",star);
        params.put("contain",et_content.getText().toString());

        Log.i("addGoodsComment",params.toString());
        if(mUploadPhotos.size() > 0){
            params.put("photo",images());
        }

        post(EApi.USER_GOODSCOMMENT, params, new EObserver() {
            @Override
            public void successful(EResponse response) {
                dismiss();
                toast(R.string.postsuccessful);
                if (endpoint == 1){
                    defaultFinish();
                    return;
                }
                Intent intent = new Intent(EvaluateActivity.this, MyOrderActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //销毁目标Activity和它之上的所有Activity，重新创建目标Activity
                toActivity(intent);
                defaultFinish();
            }

            @Override
            public void failure(String msg) {
                dismiss(msg);
            }
        });
    }

    private String images(){
        JSONArray array = new JSONArray();
        try {
            for (String img: mUploadPhotos){
                JSONObject object = new JSONObject();
                object.put("comment_image",img);
                array.put(object);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return array.toString();
    }
}
